﻿module Sustainalytics.Event {

    import Common = Sustainalytics.Common;

    // Home controller
    export class EventListController {
        public eventsTopList: any[];
        // order by column
        public eventsOrderByCol: string;
        // order by direction
        public eventsOrderByColAsc: boolean;
        public currentUTCDate: Date;
        // the selected date is used to display the latest events
        public selectedUtcDate: Date;
        //used to disabled the calendar next button
        //public disableNextButton: boolean;
        //used to disabled the calendar previous button
        public disablePreviousButton: boolean;
        // used to display the events filtered by days
        public daysForSelectedMonth: any[] = new Array;

        //Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private EventService: EventService,
            private notificationFactory: Common.INotificationFactory) {

            var ctx = this;

            $scope['eventsList'] = ctx;
            ctx.eventsOrderByCol = 'PublishedDate';
            ctx.eventsOrderByColAsc = false;

            //ctx.disableNextButton = true;
            ctx.disablePreviousButton = false;

            var date = new Date();
            ctx.eventsTopList = new Array();

            ctx.currentUTCDate = ctx.toUTCDate(date);
            ctx.selectedUtcDate = angular.copy(ctx.currentUTCDate);
            ctx.getDays();
            ctx.getEvents();
        }

        public toUTCDate = function (date) {
            var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
            return _utc;
        };

        public getDays() {
            var ctx = this; 

            ctx.daysForSelectedMonth = new Array();

            if (ctx.selectedUtcDate != null) {
                var numberDays = new Date(ctx.selectedUtcDate.getFullYear(), ctx.selectedUtcDate.getMonth()+1, 0).getDate();

                for (var i = 1; i <= numberDays; i++) {
                    var newDate = new Date(ctx.selectedUtcDate.getFullYear(), ctx.selectedUtcDate.getMonth(), i);
                    ctx.daysForSelectedMonth.push(newDate);
                }
            }
        }

        public getEvents(): ng.IPromise<{}> {
            var ctx = this;
            ctx.$rootScope['loading'] = true;
            ctx.eventsOrderByCol = 'NameLowerCase';
            ctx.eventsOrderByColAsc = true;

            var startDate = new Date(ctx.selectedUtcDate.getFullYear(), ctx.selectedUtcDate.getMonth(), 1);
            var endDate = new Date(ctx.selectedUtcDate.getFullYear(), ctx.selectedUtcDate.getMonth()+1, 1);

            var promiseGet = ctx.EventService.getEventsList(0, 1000, [ctx.eventsOrderByCol], ctx.eventsOrderByColAsc, startDate, endDate);

            //on success
            promiseGet
                .then(function (lst) {
                    for (var i in ctx.daysForSelectedMonth) {
                        ctx.eventsTopList[i] = [];
                    }
                    for (var item = 0; item < lst["items"].length; item++) {
                            var itemStartDate = new Date((lst["items"][item]).startDate.toString());
                            var itemEndDate = new Date((lst["items"][item]).endDate.toString());
                            var itemStartDay;
                            var itemEndDay;

                            if (itemStartDate < startDate && itemEndDate < endDate && startDate < itemEndDate) {
                                itemStartDay = 0;
                                itemEndDay = itemEndDate.getDate() -1;
                            }
                            if (itemStartDate < startDate && itemEndDate > endDate && startDate < itemEndDate) {
                                itemStartDay = 0;
                                itemEndDay = ctx.daysForSelectedMonth.length - 1;
                            }
                            if (itemStartDate >= startDate && itemEndDate < endDate && startDate < itemEndDate) {
                                itemStartDay = itemStartDate.getDate() - 1;
                                itemEndDay = itemEndDate.getDate() - 1;
                            }
                            if (itemStartDate > startDate && itemEndDate > endDate && startDate < itemEndDate) {
                                itemStartDay = itemStartDate.getDate() - 1;
                                itemEndDay = ctx.daysForSelectedMonth.length - 1;
                            }

                            for (var add = itemStartDay; add <= itemEndDay; add++) {
                                ctx.eventsTopList[add].push(lst["items"][item]);
                            }
                   } 
                })
                ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });
            return promiseGet;
        }

        public monthDiff(d1, d2) {
             var months;
             months = (d2.getFullYear() - d1.getFullYear()) * 12;
             months -= d1.getMonth();
             months += d2.getMonth();
             return months <= 0 ? months : months;
        }

        public addMonth() {
            var ctx = this;
            ctx.selectedUtcDate.setMonth(ctx.selectedUtcDate.getMonth() + 1);

            var diffMonth = ctx.monthDiff(ctx.currentUTCDate, ctx.selectedUtcDate);

            //if (diffMonth >= 0)
            //    ctx.disableNextButton = true;
            //else
            //    ctx.disableNextButton = false;

            if (diffMonth <= -2)
                ctx.disablePreviousButton = true;
            else
                ctx.disablePreviousButton = false;

            ctx.getDays();
            ctx.getEvents();
        }

        public decreaseMonth() {
            var ctx = this;
            ctx.selectedUtcDate.setMonth(ctx.selectedUtcDate.getMonth() - 1);

            var diffMonth = ctx.monthDiff(ctx.currentUTCDate, ctx.selectedUtcDate);

            //if (diffMonth >= 0)
            //    ctx.disableNextButton = true;
            //else
            //    ctx.disableNextButton = false;

            if (diffMonth <= -2 )
                ctx.disablePreviousButton = true;
            else
                ctx.disablePreviousButton = false;

            ctx.getDays();
            ctx.getEvents();
        }
    }

    // register controller 
    angular.module('Sustainalytics.Event').controller('EventListController', function ($rootScope: ng.IScope, $scope: ng.IScope, $q: ng.IQService, $location: ng.ILocationService, EventService, notificationFactory: Common.INotificationFactory) {
        var ctrl = new Sustainalytics.Event.EventListController($rootScope, $scope, $q, $location, EventService, notificationFactory);
        return ctrl;
    });
}  